import pymysql
#创建一个类，包含各种数据库函数的调用
class Result:
    #初始化函数，包含数据库url，密码，数据库名
    def __init__(self,**data):
        self.url = data['url']
        self.user = data['user']
        self.password =  data['password']
        self.db = data['db']
        

    def start(self):
        self.conn = pymysql.connect(host=self.url,user=self.user,password=self.password,db=self.db)
        self.cursor = self.conn.cursor()

    def rollback(self):
        self.conn.rollback()

    #查询函数，返回一个字典
    def query(self):
        self.cursor.execute("select * from leval")
        # #获取查询结果
        result = self.cursor.fetchall()
        # #关闭游标
        return result   
    
    def insert(self,**data):
        sql = "insert into leval(leval_type,leval_days,leval_desc,leval_user,reviewedBy,time) values('{leave_type}',{leave_day},'{leave_desc}','{leave_user}','{reviewedBy}','{time}')".format(leave_type= data['leave_type'],leave_day= data['leave_day'],leave_desc= data['leave_desc'],leave_user= data['leave_user'],reviewedBy = data['reviewedBy'],time=data['time'])
        self.cursor.execute(sql)
        self.conn.commit()

    def delete(self,table_name,id):
        self.cursor.execute("delete from {name} where user_id={id}".format(name=table_name,id=id))
        self.conn.commit()

    def update(self,table_name,id,**data):
        self.cursor.execute("update {name} set user_desc='{user_desc}',password='{password}',nickname='{nickname}' where user_id={id}".format(name=table_name,user_desc=data['user_desc'],password=data['password'],nickname=data['nickname'],id=id))
        self.conn.commit()
    
    def close(self):
        self.cursor.close()
        self.conn.close()

    def settings(self,**data):
        self.url = data['url']
        self.user = data['user']
        self.password = data['password']
        self.db = data['db']


 